<?php

namespace App\Http\Controllers\PhpCookBook\String;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class ExampleController extends Controller
{
	public $family = array( 
			['Hong','jia','wei'],
			['Zhang','wan','yu'],
			['Hong','He','Shan'],
			['Ke','Chun','Ling'],
			['Hong','Yan','Ni'],
			['Sun','Xiu','Bi'],
		);
    //1-27 生成逗号分隔数据
	public function fputcsv(){
		$file = './family.csv';
		$this->fputcsvAction($file);
	}
	//1-28 输出逗号分隔数据
	public function phpOutPut(){
		$file= 'php://output';
		$this->fputcsvAction($file);
	}
	//1-29 将逗号分隔数据放入一个字符串
	public function obFputcsv(){
		ob_start();
		$file = 'php://output';
		$this->fputcsvAction($file);
		$output = ob_get_contents();
		ob_end_clean();
		dd($output);
	}
	
	private function fputcsvAction($file){
		$this->fputcsvCommon($file,$this->family);
		return true;
	}
	private function fputcsvCommon($fileName,$contentArr){
		$fh = fopen($fileName,'w') or die('Can`t open '.$fileName);
		foreach($contentArr as $content){
			if(fputcsv($fh,$content) === false){
				die('Can`t write CSV line');
			}
		}
		fclose($fh) or die('Can`t close '.$fileName);
		return true;
	}
	
	//1-30 解析逗号分隔数据
	public function fgetcsv(){
		$fp = fopen('./family.csv','r') or die('Can`t open file');
		print "<table>\n";
		while($csv_line = fgetcsv($fp)){
			print "<tr>\n";
			foreach($csv_line as $key => $val){
				print "<td>". htmlentities($val). "</td>";
			}
			print "</tr>";
		}
		print "</table>";
		fclose($fp) or die('Can`t close file');
	}
}
